package com.lzh.crm.controller;

import com.alibaba.excel.EasyExcel;
import com.lzh.crm.pojo.*;
import com.lzh.crm.service.ServicesService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/services")
public class ServicesController {
    @Resource
    private ServicesService servicesService;

    //添加业务信息
    @PostMapping("/insert")
    public Result insert(@RequestBody Services services) {
        servicesService.insert(services);
        return Result.success("添加成功");
    }

    //删除业务信息
    @DeleteMapping("/delete")
    public Result delete(Integer serId){
        servicesService.delete(serId);
        return Result.success("删除成功");
    }

    //更新业务信息
    @PutMapping("/update")
    public Result update(@RequestBody Services services) {
        servicesService.update(services);
        return Result.success("修改成功");
    }

    //查询所有业务信息
    @GetMapping("/selectAll")
    public Result<List<ServicesDTO>> selectAll() {
        List<ServicesDTO> s = servicesService.selectAll();
        return Result.success(s);
    }

    //条件查询业务信息
    @GetMapping("/selectNeed")
    public Result<List<ServicesDTO>> selectNeed(Services services) {
        List<ServicesDTO> s = servicesService.selectNeed(services);
        return Result.success(s);
    }

    //导出信息
    @GetMapping("/export")
    public void exportServices(HttpServletResponse response, @RequestParam(required = false) String userId) throws IOException {
        List<Services> serList;

        // 根据 userId 筛选数据
        if (userId != null && !userId.isEmpty()) {
            serList = servicesService.selectId(userId); // 按用户 ID 查询
        } else {
            serList = servicesService.select(); // 默认查询全部（可选逻辑）
        }

        //设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        String fileName = URLEncoder.encode("业务信息表", "UTF-8").replace("\\+", "%20");
        response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xlsx");

        //根据Services字段和注解生成表头
        EasyExcel.write(response.getOutputStream(), Services.class).sheet("业务数据").doWrite(serList);
    }

    //导入信息
    @PostMapping("/input")
    public Result inputServices(@RequestParam("file") MultipartFile file) throws IOException {
        //根据注解自动映射Services的表头和字段
        List<Services> dtoList = EasyExcel.read(file.getInputStream()).head(Services.class).sheet().doReadSync();

        //将DTO转成实体
        List<Services> serList = servicesService.convertExcelDTOToServices(dtoList);

        //插入数据库
        servicesService.saveBatch(serList);

        return Result.success();
    }
}
